package com.dbq.fast.util;

import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.dbq.fast.App;
import com.dbq.fast.BuildConfig;
import com.dbq.fast.R;
import com.yiba.logutils.utils.FileUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

/**
 * Created by yuanchen on 2018/5/15.
 */

public class ShareUtil {

    public static void share2Weibo(Context context, String content) {
        boolean flag = isAvilible(context, "com.sina.weibo");
        if (!flag) return;

        Intent intent = new Intent();
        intent.setPackage("com.sina.weibo");
        intent.setAction("android.intent.action.SEND");
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, content);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void share2QQ(Context context, String content) {
        boolean flag = isAvilible(context, "com.tencent.mobileqq");
        if (!flag) return;

        ComponentName comp = new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");

        Intent intent = new Intent();
        intent.setComponent(comp);
        intent.setAction("android.intent.action.SEND");
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, content);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void share2Wx(Context context, String filePath, boolean isShareFriend) {
        boolean flag = isAvilible(context, "com.tencent.mm");
        if (!flag) return;

        ComponentName comp = null;
        if (isShareFriend) {
            comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
        } else {
            comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
        }

        Intent intent = new Intent();
        intent.setComponent(comp);
        intent.setAction("android.intent.action.SEND");
        intent.setType("image/*");
        if (!isShareFriend) {
            intent.putExtra(Intent.EXTRA_TEXT, "");
        }

        File file = new File(filePath);
        if (file.exists()) {
            Uri uri = Uri.fromFile(file);
            if(Build.VERSION.SDK_INT >= 24){
                uri = getImageContentUri(context, file);
            }
            if(uri == null) {
                ProgressDialogUtil.hideProgress();
                return;
            }
            intent.putExtra(Intent.EXTRA_STREAM, uri);
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static Bitmap draw2Bitmap(Context context, int res) {
        InputStream is = context.getResources().openRawResource(res);

        Bitmap mBitmap = BitmapFactory.decodeStream(is);

        return mBitmap;
    }

    public static String saveBitmap(Context context, Bitmap b) {
        String filePath = FileUtil.getTempDirPath(context) + "unicorn_share.png";
        if(BuildConfig.DEBUG){
            Log.e("yc_", "filePath:"+filePath);
        }
        File f = new File(filePath);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            b.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return filePath;
    }

    public static Bitmap mergeBitmap(Bitmap bitmap1, Bitmap bitmap2) {
        Bitmap bitmap = Bitmap.createBitmap(bitmap1.getWidth(), bitmap1.getHeight(), bitmap1.getConfig());
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(bitmap1, new Matrix(), null);
        canvas.drawBitmap(bitmap2, 0, bitmap1.getHeight() - bitmap2.getHeight(), null);
        return bitmap;
    }

    public static Bitmap mergeBitmapCustom(Bitmap bitmap1, Bitmap bitmap2, int left, int top) {
        Bitmap bitmap = Bitmap.createBitmap(bitmap1.getWidth(), bitmap1.getHeight(), bitmap1.getConfig());
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(bitmap1, new Matrix(), null);
        canvas.drawBitmap(bitmap2, left, top, null);
        return bitmap;
    }

    public static Bitmap text2Bitmap(Context context, TextView tv) {
        tv.setText(context.getString(R.string.wx_invite_content, "20%"));
        tv.setDrawingCacheEnabled(true);
        tv.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());
        Bitmap bitmap = Bitmap.createBitmap(tv.getDrawingCache());
        return bitmap;
    }

    /**
     * 判断相对应的APP是否存在
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isAvilible(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();

        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            if (((PackageInfo) pinfo.get(i)).packageName
                    .equalsIgnoreCase(packageName))
                return true;
        }

        Toast.makeText(context, context.getString(R.string.not_install_app), Toast.LENGTH_SHORT).show();
        ProgressDialogUtil.hideProgress();
        return false;
    }

    //兼容8.0问题
    private static Uri getImageContentUri(Context context, File imageFile) {
        try {
            String filePath = imageFile.getAbsolutePath();
            Cursor cursor = context.getContentResolver().query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    new String[]{MediaStore.Images.Media._ID},
                    MediaStore.Images.Media.DATA + "=? ",
                    new String[]{filePath}, null);

            if (cursor != null && cursor.moveToFirst()) {
                int id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/images/media");
                return Uri.withAppendedPath(baseUri, "" + id);
            } else {
                if (imageFile.exists()) {
                    ContentValues values = new ContentValues();
                    values.put(MediaStore.Images.Media.DATA, filePath);
                    return context.getContentResolver().insert(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                } else {
                    return null;
                }
            }
        }catch (Exception e){
            Toast.makeText(App.getContext(), App.getContext().getString(R.string.tip_open_storage_permission), Toast.LENGTH_SHORT).show();
        }
        return null;
    }

}
